<?php
class Application_Model_Users extends My_Model_Abstract
{
    const USER_NAMESPACE = 'zs_User';

    protected $_session;

    protected $_mainTable = 'admin';

    //protected $_fetchMode = Zend_Db::FETCH_OBJ;

    protected function _construct()
    {
        $this->setIdFieldName('p_admin');
    }

    protected function _loadByUserName($username)
    {
        $select = $this->getAdapter()->select();
        $select->from($this->_mainTable);
        $select->where('userid=?', $username);
        $result = $this->getAdapter()->fetchRow($select);
        if ($result) {
            $this->_loadUserData($result);
        }
        return $this;
    }

    protected function _loadByUserId($userId)
    {
        $select = $this->getAdapter()->select();
        $select->from($this->_mainTable);
        $select->where($this->getIdFieldName() . '=?', $userId);
        $result = $this->getAdapter()->fetchRow($select);
        if ($result) {
            $this->_loadUserData($result);
        }
        return $this;
    }

    protected function _loadUserData($data)
    {
        $this->setData($data);
        return $this;
    }

    protected function _validatePassword($password)
    {
        if ($this->_hashPassword($password) == $this->getPassword()) {
            $this->unsPassword();
            return true;
        }
        return false;
    }

    protected function _hashPassword($password)
    {
        return md5($password);
    }

    public function getSession()
    {
        if (empty($this->_session)) {
            $this->_session = new Zend_Session_Namespace(self::USER_NAMESPACE);
        }
        return $this->_session;
    }

    public function isLoggedIn()
    {
        if (isset($this->getSession()->isLoggedIn)) {
            return $this->getSession()->isLoggedIn;
        }
        return false;
    }

    public function setIsLoggedIn($isLoggedIn = false)
    {
        $this->getSession()->isLoggedIn = $isLoggedIn;
        return $this;
    }

    public function login($username, $password)
    {
        $this->_loadByUserName($username);
        if ($this->getId() && $this->_validatePassword($password)) {
            /* login success */
            $this->setIsLoggedIn(true);
            $this->getSession()->userId = $this->getId();
        } else {
            /* login fail */
            $flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
            $flashMessenger->setNamespace('error')->addMessage('Invalid Username or Password');
        }
    }

    public function logout()
    {
        Zend_Session::namespaceUnset(self::USER_NAMESPACE);
    }

    public function initUser()
    {
        if ($this->getSession()->userId) {
            $this->setId($this->getSession()->userId);
            $this->_loadByUserId($this->getId())->unsPassword();
        }
        return $this;
    }
}